/**
 * Pinganfu.com Inc.
 * Copyright (c) 2003-2013 All Rights Reserved.
 */
package com.huatai.vba.grovvy.base;

import org.springframework.core.io.ResourceLoader;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.support.*;
import org.springframework.stereotype.Component;

/**
 * 通过继承<code>ScriptFactoryPostProcessor</code>, 实现定制的Groovy脚本后处理器，用来定制数据库的脚本加载处理
 */
@Component
public class CustomScriptFactoryPostProcessor extends ScriptFactoryPostProcessor {

	/**
	 * @see org.springframework.scripting.support.ScriptFactoryPostProcessor#convertToScriptSource(java.lang.String,
	 *      java.lang.String, org.springframework.core.io.ResourceLoader)
	 */
	protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator,
			ResourceLoader resourceLoader) {
		if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
			return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
		} else if (scriptSourceLocator.startsWith(GroovyConstant.SCRIPT_SOURCE_PREFIX)) {
			String scriptName = getScriptName(scriptSourceLocator);
			return new DatabaseScriptSource(scriptName);
		} else {
			return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
		}
	}

	/**
	 * 获取脚本名称
	 * 
	 * @param scriptSourceLocator
	 * @return
	 */
	private String getScriptName(String scriptSourceLocator) {
		String scriptName = scriptSourceLocator.replace(GroovyConstant.SCRIPT_SOURCE_PREFIX, "");
		return scriptName.toLowerCase();
	}

	/**
	 * 测试接口
	 * 
	 * @param beanName
	 * @param scriptSourceLocator
	 * @param resourceLoader
	 * @return
	 */
	public ScriptSource testScriptSource(String beanName, String scriptSourceLocator, ResourceLoader resourceLoader) {
		return this.convertToScriptSource(beanName, scriptSourceLocator, resourceLoader);
	}

}
